﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Hopscotch.Common.Contracts.EnqService;
using Hopscotch.Domain.Enquiry;
using Hopscotch.Domain.Finance;
using Hopscotch.Server.Common.Contracts;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;

namespace Hopscotch.Server.EnqSignalRHost.Hubs
{
    /// <summary>
    /// SignalR Hub to implement ITradeEnqService
    /// </summary>
    [HubName(HubNames.TradeEnqHub)]
    public class TradeEnqHub : HubBase<ITradeEnqRemoteClient>, ITradeEnqService
	{
        private readonly IInternalInstrumentEnqService instrumentService;
        private readonly IInternalTradeEnqService intTradeEnqService;        

        public TradeEnqHub(
            IInternalInstrumentEnqService instrumentService,
            IInternalTradeEnqService intTradeEnqService)
		{
            this.intTradeEnqService = intTradeEnqService;
            this.instrumentService = instrumentService;
		}

		public void StartQuery(string query)
		{
			var connectionId = this.Context.ConnectionId;
			var user = this.Context.User;

			//temp
            List<TradeEnq> trades = intTradeEnqService.Get(DateTime.Now.Date);
            foreach (var tradeEnq in trades)
            {
                this.Clients.Caller.TradeMessage(query, tradeEnq);
            }
        }

        public void StopQuery(string query)
        {
        }
                
        public async Task<Trade> GetWithInstrument(int id)
        {            
            var tradeEnq = intTradeEnqService.Get(id);
            Trade trade = tradeEnq.UpcastToTrade();

            if (trade.InstrumentId.HasValue)
            {
                trade.Instrument = await Task.Run<Instrument>(() => instrumentService.Get(trade.InstrumentId.Value));
            }

            return trade;
        }

    }
}
